<?php
session_start();
include_once("account_utils.php");
include_once("../db_connection.php");
include_once("major_reqs.php");


// We initially have no database connection.
$db = NULL;
if(isset($_GET['logout'])) gpp_logout();

// If the user is logged in, we want to send them to the page where
// they can actually use the application.
if(!gpp_is_authenticated() && $page != 'Entrance')
{
	gpp_redirect('Entrance');
}

if(gpp_user_has_no_schedule())
{
	gpp_redirect("enter_schedule");
}

// This is where we map locations to script names.
function gpp_redirect($page_name)
{
	$locations = array('main' => '/main.php', 'entrance' => '/index.php', 'profile' => '/profile.php');
	
	header('Location:' . $locations[strtolower($page_name)]);
	die();
}

// Make a query to the DB
// Ref http://www.php.net/manual/en/function.mysql-query.php


function get_semester_name($i)
{
	//$semesters = array("S10", "F10", "S11", "F11", "S12", "F12", "S13", "F13", "S14", "F14", "S15", "F15");
	$semesters = array("Spring 2010", "Fall 2010", "Spring 2011", "Fall 2011", "Spring 2012", 
	                "Fall 2012", "Spring 2013", "Fall 2013", "Spring 2014", "Fall 2014", "Spring 2015", "Fall 2015");

	
	return $semesters[$i];
}

// This function must query the database and determine if the user has
// inputted any classes into the class database.
function gpp_user_has_no_schedule()
{
	get_database_connection();
	
	// ADD QUERY TO SEE IF THERE IS NO ENTRY IN THE STUDENT COURSE HISTORY
	
	return false;
}


function gpp_classes_by_semester_json()
{
	return gpp_get_courses(-2, $_SESSION['semesters_left']);
}

function gpp_get_courses($start, $end)
{
	$db = get_database_connection();

	// Get the list of course IDs & their associate semesters, grades, etc that the logged in student
	// has in the database
	
	$semesters = array();	
	
	for($semester=$start; $semester < $end; $semester++)
	{	
		// add json preamble for a semester here. once we are done, we will have 
		// one for each semester 0-semesters_left. We can index by semester. 
		
		$query = sprintf("SELECT * FROM history WHERE student_id = '%s' AND semester = '%s' ORDER BY course_id ASC;", $_SESSION['id'], $semester);
		$result = mysql_query($query);
	
		gpp_print_sql_error($result, $query);	
		
		$this_semester = array();
	
		// For each of the courses the student has taken, get a json piece for it.
		while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
		    
		    $this_semester[] = get_course_array($row['course_id']);

		}
		
		$semesters["s" . (string)$semester] = $this_semester;
	}
	
	return json_encode($semesters);
}


function gpp_get_remaining_reqs()
{
    $history = json_decode(gpp_history_json());
        
    $courses = array();
    $courses_to_take = array();
    
    foreach($history as $semester)
    {
        foreach($semester as $class)
        {
            $course = new Course($class->acronym, $class->number);
            $courses[] = $course;
        }
    }
    
    $pursuing = $_SESSION['pursuing'];
    
    if($pursuing == "CMSC" || $pursuing == "CMSCIS")
    {
        $reqs = new CMSCMajorRequirements();
        foreach($courses as $course)
        {
            $reqs->add_course($course);
        }
        
        $courses_to_take = array_merge($courses_to_take, $reqs->get_remaining_courses());
    }
    
    if($pursuing != "CMSC")
    {
        $reqs = new ISMajorRequirements();
        foreach($courses as $course)
        {
            $reqs->add_course($course);
        }
        
        $courses_to_take = array_merge($courses_to_take, $reqs->get_remaining_courses());
    }
    
    if($pursuing == "ISCMSCminor")
    {
        $reqs = new CMSCMinorRequirements();
        foreach($courses as $course)
        {
            $reqs->add_course($course);
        }
        
        $courses_to_take = array_merge($courses_to_take, $reqs->get_remaining_courses());
    }
    
    $courses_to_take = array_unique($courses_to_take);
   
    $courses = array();
    foreach($courses_to_take as $course)
    {
        list($prefix, $number) = split(" ", $course);
        $courses[] = json_decode(get_course_json_acronym($prefix, $number));
    }
    
    return json_encode($courses);
}



function gpp_search_classes_json($search_major, $search_terms)
{
    $major = mysql_real_escape_string($search_major);
    $terms = mysql_real_escape_string($search_terms);
        
    $query = "SELECT id, acronym, number, title, description, credits, prereqs FROM courses WHERE ";
    $query .= sprintf("acronym = '%s' AND (description LIKE '%%%s%%' OR title LIKE '%%%s%%')",
            $major, $terms, $terms);

    $result = mysql_query($query);

    gpp_print_sql_error($result, $query);	
    
    $courses = array();

    // For each of the courses the student has taken, get a json piece for it.
    while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
        
        $course = array('id' => $row[0], 'acronym' =>  $row[1], 'number' => $row[2], 
	    'title' => $row[3], 'description' => $row[4], 'credits' => $row[5],
	    'prereqs' => $row[6]);
        
        $courses[] = $course;

    }
    
    return json_encode($courses);

}



function gpp_history_json()
{
	return gpp_get_courses(-2, 0);
}

// This takes JSON data, and completely wipes the database for future classes,
// and replaces the classes in the future with the ones in the data 
function gpp_save_schedule_json($data)
{
	$db = get_database_connection();

	// output should contain .message and .data
	
	$output = array();
	$output["message"] = "";
	
	$query = sprintf("DELETE FROM history WHERE student_id = '%s'", $_SESSION['id']);
	$result = mysql_query($query);
	
	if (!$result) 
	{
		$output["message"] .= 'Save schedule.. ';
	    $output["message"] .= 'Invalid query: ' . mysql_error() . "\n";
	    $output["message"] .= 'Whole query: ' . $query;
	}
	
	$output["message"] .= gpp_add_courses_json($data);
		
	$output["data"] = json_decode(gpp_classes_by_semester_json());
	
	return json_encode($output);
}

// This takes JSON data, and completely wipes the database for past classes,
// and replaces the classes in the past with the ones in the data 
function gpp_save_history_json($data)
{
	$db = get_database_connection();

	// output should contain .message and .data
	
	$output = array();
	$output["message"] = "";
	
	$query = sprintf("DELETE FROM history WHERE student_id = '%s' AND semester < 0", $_SESSION['id']);
	$result = mysql_query($query);
	
	if (!$result) 
	{
		$output["message"] .= 'Save history.. ';
	    $output["message"] .= 'Invalid query: ' . mysql_error() . "\n";
	    $output["message"] .= 'Whole query: ' . $query;
	}
	
	$output["message"] .= gpp_add_courses_json($data);

	$output["data"] = json_decode(gpp_history_json());
	
	return json_encode($output);
}


function gpp_add_courses_json($data)
{
	$db = get_database_connection();

	$schedule = json_decode($data);
	
	$message = "";
	
	for($i=0; $i < count($schedule); $i++)
	{	
		$item = $schedule[$i];

		$semester = substr($item->sem, 1);
		$course = $item->id;
		
		$query = sprintf("INSERT INTO history (student_id, course_id, semester) VALUES (%s, %s, %s);", $_SESSION['id'], $course, $semester);
		$result = mysql_query($query);
			
		if (!$result) 
		{
			$message .= 'Invalid query: ' . mysql_error() . "\n";
			$message .= 'Whole query: ' . $query;
		}
			
	}

	return $message;
}


// Pull a course from the database and format it how we want it for JSON purposes.
function get_course_array($course_id)
{
	$db = get_database_connection();
	
	$query = sprintf("SELECT id, acronym, number, title, description, credits, prereqs FROM courses WHERE id = '%s' ORDER BY number ASC;", $course_id);
	$result = mysql_query($query);
	
	gpp_print_sql_error($result, $query);
	
	// Get the 
	if($row = mysql_fetch_array($result, MYSQL_BOTH)) {
	    
	    $course = array('id' => $row[0], 'acronym' =>  $row[1], 'number' => $row[2], 
	    'title' => $row[3], 'description' => $row[4], 'credits' => $row[5],
	    'prereqs' => $row[6]);
	}
	else
	{
		$course = array('id' => '-1', 'acronym' => 'ERR', 'number' => '000', 
		        'title' => "Error. Contact chris.cahoon@gmail.com", 'description' => "This is an error.", 
		        'credits' => "0", 'prereqs' => "");
    }
	
	return $course;
}

// Pull a course from the database and format it how we want it for JSON purposes.
function get_course_json_acronym($acronym, $number)
{
	$db = get_database_connection();
	
	$query = sprintf("SELECT id, acronym, number, title, description, credits, prereqs FROM courses WHERE acronym = '%s' AND number = '%s'", $acronym, $number);
	$result = mysql_query($query);
	
	gpp_print_sql_error($result, $query);
	
	if($row = mysql_fetch_array($result, MYSQL_BOTH)) {
	    
	    $course = array('id' => $row[0], 'acronym' =>  $row[1], 'number' => $row[2], 
	    'title' => $row[3], 'description' => $row[4], 'credits' => $row[5],
	    'prereqs' => $row[6]);
	}
	else
	{
		$course = array('id' => '-1', 'acronym' => 'ERR', 'number' => '000', 
		        'title' => "Error. Contact chris.cahoon@gmail.com", 'description' => "This is an error.", 
		        'credits' => "0", 'prereqs' => "");
	}
	
	return json_encode($course);
}

function gpp_set_prereqs($data)
{
	$db = get_database_connection();
	
	$vals = json_decode($data);
	
	$course_list = mysql_real_escape_string(trim($vals->course_list));
	
	$query = sprintf("UPDATE courses SET prereqs = '%s' WHERE id = '%s'", $course_list, (int)($vals->id));
	
	$result = mysql_query($query);
	
	$output = array();
	$output["message"] = "query: " . $query . "\n";
	
	if (!$result) 
	{
		$output["message"] .= 'Save schedule.. ';
	    $output["message"] .= 'Invalid query: ' . mysql_error() . "\n";
	    $output["message"] .= 'Whole query: ' . $query;
	}
		
	$output['message'] .= $query;	
	return json_encode($output);
}

function get_acronyms_for_display()
{
	// This gets the list of acronyms for the drop down menu. We can reuse this because it is\
	// always the same.
	$acronyms = "";
	
	$db = get_database_connection();
	$query = sprintf("SELECT DISTINCT acronym FROM courses");
	$result = mysql_query($query);
	if(!$result) 
	{
		mysql_free_result($result);
		die("Could not get acronyms. Please contact chris.cahoon@gmail.com");
	}
	
	$acronyms = '<option value="Choose">Choose</option>\n';
	
	while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
	    $acronyms .= sprintf("<option value=\"%s\">%s</option>", $row[0], $row[0]);
	}
	$acronyms .= "\n";

	return $acronyms;
}


// From http://www.linuxjournal.com/article/9585
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

function display_pursuing()
{
	$display = "";
	switch($_SESSION['pursuing'])
	{
		case "CMSC": $display = "Major: CMSC"; break;
		case "CMSCIS": $display = "Major: CMSC and IS"; break;
		case "IS": $display = "Major: IS"; break;
		case "ISCMSCminor": $display = "Major: IS&nbsp;&nbsp;&nbsp;&nbsp;Minor: CMSC"; break;
	}
	
	return $display;
}


// These functions output common HTML between the pages.
function gpp_print_header($page_name, $welcome)
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>greenPaperPlus | <?php echo  $page_name ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<link rel="stylesheet" type="text/css" href="/media/style.css" />
<link rel="stylesheet" href="/media/print_style.css" type="text/css" media="print" />

<script language="Javascript" src="/includes/json2.js"></script>
<script language="Javascript" src="/includes/jquery.js"></script>
<script language="Javascript" src="/includes/jquery.simplemodal.js"></script>
<script language="Javascript" src="/includes/gpp.js"></script>


<script type="text/javascript">

$(function() {
	$("#help_button").click(function(){
		$.ajax({
  			url: "/help.html",
  			cache: false,
  			success: function(html){
    				$.modal(html);
  				}
		});
	})
})



</script>

</head>
<body>
<?php if(gpp_is_authenticated()) { ?>
<ul id="navigation">
<li><a href="/profile.php">Profile</a></li>
<li><a href="/greensheet.php">Green Sheet/Course History</a></li>
<li><a href="/schedule.php">Schedule</a></li>
<li><!-- <a href="/help.php">--><a id="help_button" href="#">Help</a> </li>
<li><a href="/?logout">Log out</a></li>
</ul>
<?php } ?>

<h1 id="gpp_title"><a href="/">greenPaperPlus</a></h1>

<?php if(gpp_is_authenticated()) { ?>
<p><?php echo sprintf("%s %s (%s)&nbsp;&nbsp;&nbsp;&nbsp;%s&nbsp;&nbsp;&nbsp;&nbsp;Semesters Remaining: %s", 
						$_SESSION['name_first'], $_SESSION['name_last'], $_SESSION['email'], display_pursuing(), $_SESSION['semesters_left']);?>  
</p>
<?php } ?>
<h1><?php echo $welcome ?></h1>

<?php

}

function gpp_print_footer()
{

?>
<div id="footer">&copy; 2009 Team 3, CMSC 345 F2009 under Zary Segall</div>
</body>
</html>
<?php

}

?>